<template>
  <div class="page-view">
    <div class="map-view">
      <MyMap ref="myMap">
        <MapGeo v-if="layers" :json="layers" :stroke="{ color: '#f0f', width: 2 }"></MapGeo>
        <MapHeat v-if="dataHeat" :data="dataHeat"></MapHeat>
        <MapMarker
          v-if="dataMarker"
          :data="dataMarker"
          :cluster="false"
          :scale="0.8"
          :distance="10"
          @show="clickPoint"
        >
          <div v-if="searchType === 1">
            <a-descriptions :column="1" bordered size="small" title="样点信息">
              <a-descriptions-item label="样本编号" span="1">
                {{ markerInfo['ydbh'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="行政区" span="1">
                {{ markerInfo['zldwmc'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="指标值" span="1">
                {{ markerInfo['field'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="莫兰指数" span="1">
                {{ markerInfo['moranI'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="z得分" span="1">
                {{ markerInfo['zscore'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="P值" span="1">
                {{ markerInfo['pvalue'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="聚类和异常值类型" span="1">
                {{ markerInfo['typeText'] || '' }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
          <div v-if="searchType === 2">
            <a-descriptions title="位置信息" :column="1" bordered size="small">
              <a-descriptions-item label="样点编号" :span="1">
                {{ markerInfo['ydbh'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="坐落单位名称" :span="1">
                {{ markerInfo['zldwmc'] }}
              </a-descriptions-item>
              <a-descriptions-item label="经纬度" :span="1">
                {{ markerInfo['jd'], markerInfo['wd'] }}
              </a-descriptions-item>
              <a-descriptions-item label="土地利用类型" :span="1">
                {{ markerInfo['tdlylx'] || '' }}
              </a-descriptions-item>
            </a-descriptions>
            <br/>
            <a-descriptions title="土壤理化检测指标" :column="1" bordered size="small" style="margin-top: 10px;">
              <a-descriptions-item label="阳离子交换量" :span="1">
                {{ markerInfo['cec'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="有机质" :span="1">
                {{ markerInfo['om'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="全氮" :span="1">
                {{ markerInfo['tn'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="全磷" :span="1">
                {{ markerInfo['tp'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="全钾" :span="1">
                {{ markerInfo['tk'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="有效磷" :span="1">
                {{ markerInfo['ap'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="缓效钾" :span="1">
                {{ markerInfo['sk'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="速效钾" :span="1">
                {{ markerInfo['ak'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总铬" :span="1">
                {{ markerInfo['cr'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总镉" :span="1">
                {{ markerInfo['cd'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总铅" :span="1">
                {{ markerInfo['pb'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总砷" :span="1">
                {{ markerInfo['as2'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总汞" :span="1">
                {{ markerInfo['hg'] || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="总镍" :span="1">
                {{ markerInfo['ni'] || '' }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </MapMarker>
      </MyMap>
    </div>
    <!-- 图例 -->
    <div class="map-leg" v-if="searchType === 1">
      <template v-for="item in Icon">
        <div class="img" :key="item.text">
          <span class="map-leg-icon" :style="{ background: item.color }"></span>
          <span>{{ item.text }}</span>
        </div>
      </template>
    </div>

    <div class="select-filds">
      <a-form :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
        <a-form-item label="区域">
          <a-tree-select
            v-model="searchForm.xzqdm"
            :treeData="city"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :replaceFields="{
              value: 'dicCode',
              label: 'dicValue'
            }"
            placeholder="请选择区域"
            style="width: 100%"
          >
            <!-- allow-clear -->
          </a-tree-select>
        </a-form-item>
        <a-form-item label="指标类型">
          <a-select
            v-model="searchForm.type"
            style="width: 100%"
            @change="changeType"
          >‘
            <template v-for="item in type">
              <a-select-option :key="item.value" :value="item.value">{{
                item.text
              }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="指标">
          <a-select v-model="searchForm.field" style="width: 100%">
            <template v-for="item in type[searchForm.type].children">
              <a-select-option :key="item.value" :value="item.value">{{
                item.text
              }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <div style="text-align: center">
          <a-space>
            <a-button type="primary" @click="handleClick(1)"> 聚类分析 </a-button>
            <a-button type="primary" @click="handleClick(2)"> 统计分析 </a-button>
          </a-space>
        </div>
      </a-form>
    </div>

    <div class="reslut-filds" v-if="scatterShow">
      <div class="chart-filds">
        <scatter :data="valueData" :filed="searchForm.field"></scatter>
      </div>
    </div>

    <div class="result-icon">
      <div class="icon-item">
        <a-icon type="table" :class="{ active: showTable }" @click="showTable = !showTable" />
      </div>
    </div>

    <a-drawer
      placement="bottom"
      :visible="showTable"
      :mask="false"
      @close="showTable = !showTable"
      :height="380"
      :bodyStyle="{ paddingBottom: '0px' }"
    >
      <div slot="title" style="display: flex; justify-content: space-between">
        <div>分析结果</div>
        <div style="margin-right: 40px">
          <a-button type="link" size="small" icon="download" @click="exportExcel">导出</a-button>
        </div>
      </div>
      <a-table
        rowKey="ydbh"
        :dataSource="valueData"
        size="small"
        :bordered="false"
        :columns="columns"
        :pagination="pagination"
        :customRow="customRow"
      >
      </a-table>
    </a-drawer>
    <div class="loading-warp" v-if="showLoading">
      <div class="loading-out">
        <Loading></Loading>
        <div class="text">分析中</div>
      </div>
    </div>
  </div>
</template>

<script>
import { MyMap, MapGeo, MapMarker, MapHeat } from '@/map'
import { queryAllcity, queryCityGeo } from '@/api/common'
import { clusterOutlierAnalyst, featureAnalysis } from '@/api/analysis'
import { export_array_to_excel as exportArrayToExcel } from '@/utils/excel'
import scatter from './scatter'

import Loading from '@/components/loading'
// import cyan from '@/assets/icon/cyan.png'
// import red from '@/assets/icon/red.png'
// import orange from '@/assets/icon/orange.png'
import { queryPointList } from '@/api/list'

const Icon = {
  HH: {
    text: '高-高',
    color: '#FF0000'
  },
  HL: {
    text: '高-低',
    color: '#FF9696'
  },
  LH: {
    text: '低-高',
    color: '#9696FF'
  },
  LL: {
    text: '低-低',
    color: '#0000FF'
  },
  default: {
    text: '不显著',
    color: '#BEBEBE'
  }
}

const type = {
  lh: {
    text: '土壤理化性质',
    value: 'lh',
    children: [
      { text: '酸碱度', value: 'ph' },
      { text: '阳离子交换量', value: 'cec' }
    ]
  },
  yf: {
    text: '土壤养分',
    value: 'yf',
    children: [
      { text: '有机质', value: 'om' },
      { text: '全氮', value: 'tn' },
      { text: '全磷', value: 'tp' },
      { text: '全钾', value: 'tk' },
      { text: '有效磷', value: 'ap' },
      { text: '速效钾', value: 'ak' },
      { text: '有效硫', value: 'as1' }
    ]
  },
  hj: {
    text: '土壤环境',
    value: 'hj',
    children: [
      { text: '镉', value: 'cd' },
      { text: '汞', value: 'hg' },
      { text: '砷', value: 'as2' },
      { text: '铅', value: 'pb' },
      { text: '铬', value: 'cr' },
      { text: '镍', value: 'ni' }
    ]
  }
}

const lhColumns = [
  {
    title: '序号',
    key: 'index',
    fixed: true,
    customRender: (text, record, index) => index + 1
  },
  {
    title: '指标',
    key: 'quota',
    dataIndex: 'quota'
    // customRender: (text) => text.toUpperCase()
  },
  {
    title: '最大值',
    dataIndex: 'max',
    key: 'max',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '最小值',
    dataIndex: 'min',
    key: 'min',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '均值',
    dataIndex: 'avg',
    key: 'avg',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '方差',
    dataIndex: 'fangcha',
    key: 'fangcha',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '中位数',
    dataIndex: 'fenweishu',
    key: 'fenweishu',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '偏度',
    dataIndex: 'piandu',
    key: 'piandu',
    customRender: (text) => text.toFixed(2)
  },
  {
    title: '峰度',
    dataIndex: 'fengdu',
    key: 'fengdu',
    customRender: (text) => text.toFixed(2)
  }
]

const jlColumns = [
  {
    title: '序号',
    key: 'index',
    fixed: true,
    customRender: (text, record, index) => index + 1
  },
  {
    title: '样点编号',
    dataIndex: 'ydbh',
    key: 'ydbh'
  },
  {
    title: '行政区',
    dataIndex: 'zldwmc',
    key: 'zldwmc'
  },
  {
    title: '指标值',
    dataIndex: 'field',
    key: 'field'
  },
  {
    title: '莫兰指数',
    dataIndex: 'moranI',
    key: 'moranI'
  },
  {
    title: 'P值',
    dataIndex: 'pvalue',
    key: 'pvalue'
  },
  {
    title: 'z得分',
    dataIndex: 'zscore',
    key: 'zscore'
  },
  {
    title: '聚类和异常值类型',
    dataIndex: 'typeText',
    key: 'typeText'
  }
]

export default {
  name: 'Interpolation',
  components: {
    MyMap,
    MapMarker,
    MapGeo,
    MapHeat,
    Loading,
    scatter
  },
  data () {
    this.type = type
    this.Icon = Icon
    return {
      city: [],
      showLoading: false,
      layers: undefined,
      searchForm: {
        xzqdm: '110117',
        type: 'lh',
        field: 'ph'
      },
      showTable: false,
      pagination: {
        pageSize: 5
      },
      columns: jlColumns,
      valueData: undefined,
      searchType: 1,
      dataMarker: undefined,
      markerInfo: {},
      dataHeat: undefined,
      scatterShow: false
    }
  },
  created () {
    this.fetchCity()
    this.handleClick()
  },
  methods: {
    clickPoint (marker) {
      this.markerInfo = {
        ...marker.items[0]
      }
      this.pointHightlight(marker.items[0])
    },
    /**
     * 点位高亮
     * @param record
     */
    pointHightlight (record) {
      // 高亮选中
      const marker = this.dataMarker.find((item) => item.ydbh === record.ydbh)
      this.dataMarker = this.dataMarker
        .filter((item) => item.ydbh !== record.ydbh)
        .map((marker) => {
          return {
            ...marker,
            style: {
              fill: marker.type ? Icon[marker.type].color : Icon['default'].color,
              radius: 5
            }
          }
        })
      this.dataMarker.push({
        ...marker,
        style: undefined,
        src: ''
      })
      this.$refs.myMap.moveTo([marker.coordinate[0], marker.coordinate[1]])
    },
    async fetchCity () {
      try {
        const { data } = await queryAllcity()
        this.city = data[0].children
      } catch (err) {
        throw err
      }
    },
    handleChange () {
      this.layers = undefined
      if (this.searchForm.xzqdm) {
        queryCityGeo({
          xzqdm: this.searchForm.xzqdm
        }).then((res) => {
          this.layers = JSON.parse(res.data)
        })
      }
    },
    changeType () {
      this.searchForm.field = this.type[this.searchForm.type].children[0].value
    },
    handleClick (type = 1) {
      this.handleChange()

      this.scatterShow = false
      this.showLoading = true
      this.dataMarker = undefined
      this.dataHeat = undefined
      this.searchType = type

      if (type === 1) {
        this.clusterOutlier()
      } else {
        this.feature()
      }
    },
    /**
     * 特征分析
     */
    async feature () {
      try {
        queryPointList({
          xzqdm: this.searchForm.xzqdm
        }).then((res) => {
          this.dataMarker = res.data.filter(item => {
            return !(/^01\d/.test(item.tdlylx))
          }).map((marker) => {
            return {
              ...marker,
              coordinate: [Number(marker.jd), Number(marker.wd)],
              style: {
                fill: Icon['default'].color,
                radius: 5
              }
            }
          })
        })

        const { data } = await featureAnalysis({
          xzqdm: this.searchForm.xzqdm,
          quotas: this.searchForm.field
          // quotas: type[this.searchForm.type].children.map(item => item.value).join(',')
        })
        this.showTable = true
        this.columns = lhColumns
        this.valueData = data.map((item, key) => {
          return {
            id: key,
            ...item
          }
        })
        this.showLoading = false
      } catch (err) {
        this.showLoading = false
        this.$message.error(err.data || '分析失败')
      }
    },
    /**
     * 聚类分析
     */
    async clusterOutlier () {
      try {
        const { data } = await clusterOutlierAnalyst({
          xzqdm: this.searchForm.xzqdm,
          field: this.searchForm.field.toUpperCase()
        })
        this.dataMarker = data.map((marker) => {
          return {
            coordinate: [marker.jd, marker.wd],
            // src: Icon[marker.type] || cyan,
            style: {
              fill: marker.type ? Icon[marker.type].color : Icon['default'].color,
              radius: 5
            },
            zldwmc: marker.zldwmc,
            field: Number(marker['field']).toFixed(3),
            ydbh: marker.ydbh,
            moranI: marker.moranI.toFixed(3),
            zscore: marker.zscore.toFixed(3),
            pvalue: marker.pvalue.toFixed(3),
            type: marker.type,
            typeText: marker.type ? Icon[marker.type].text : Icon['default'].text
          }
        })
        // console.log(this.dataMarker)
        this.dataHeat = this.dataMarker
        // this.dataHeat = data.filter(item => ['HH', 'HL', 'LH', 'LL'].includes(item.type)).map(marker => {
        //   return {
        //     coordinate: [marker.jd, marker.wd]
        //   }
        // })
        this.valueData = this.dataMarker
        this.columns = jlColumns
        this.showTable = true
        this.showLoading = false
        this.scatterShow = true
      } catch (err) {
        this.showLoading = false
        this.$message.error(err.data || '分析失败')
      }
    },

    // 行点击
    customRow (record) {
      return {
        on: {
          click: () => {
            // 统计表格
            if (this.searchType === 2) {
              return false
            }
            this.pointHightlight(record)
          }
        }
      }
    },
    // 导出excel
    exportExcel () {
      if (!this.valueData.length) {
        this.$message.error('无导出数据')
        return false
      }
      exportArrayToExcel({
        sheet: [
          {
            columns: this.columns,
            data: this.valueData,
            sheetName: this.searchForm.xzqdm
          }
        ],
        filename: '分析结果'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.page-view {
  position: relative;
  height: 100%;
  .map-view {
    position: absolute;
    top: -24px;
    right: -24px;
    bottom: -24px;
    left: -24px;
  }
}
.select-filds {
  position: absolute;
  top: 0;
  right: 0;
  padding: 24px;
  width: 360px;
  border-radius: 4px;
  background: #ffffff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
}
.group {
  font-size: 16px;
}
.loading-warp {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.03);
  .loading-out {
    display: inline-block;
    padding: 16px 24px;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.5);
  }
  .text {
    text-align: center;
    color: #ffffff;
  }
}
.reslut-filds {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  display: flex;
  // width: 360px;
  // height: 300px;
  background: #ffffff;
  .chart-filds {
    // // position: absolute;
    // top: 20px;
    // right: 20px;
    // z-index: 2;
    width: 340px;
    height: 340px;
    // background: #ffffff;
  }
}
.result-icon {
  position: absolute;
  top: 40%;
  right: 0;
  .icon-item {
    margin: 8px 0;
    padding: 4px 8px;
    font-size: 20px;
    font-weight: bold;
    border-radius: 4px;
    background: #ffffff;
  }
  .active {
    color: @primary-color;
  }
}
.map-leg {
  position: absolute;
  right: 0;
  bottom: 24px;
  padding: 8px 16px;
  border-radius: 4px;
  background: #ffffff;
  .img {
    padding: 8px 0;
  }
  img {
    width: 30px;
  }
  span {
    padding-left: 8px;
  }
  .map-leg-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    vertical-align: middle;
  }
}
</style>
